﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MegavaniaX
{
    /// <summary>
    /// A messaging helper for objects with typical messaging concerns.
    /// </summary>
    public class MessagingHelper
    {
        /// <summary>
        /// A small struct that contains event listeners and their corresponding types.
        /// </summary>
        private struct CallbackWithType
        {
            public MegavaniaEventCallback callback;
            public MegavaniaEventType type;
            public string ListenerName;
        }

        /// <summary>
        /// A list of event listeners subscribed to this object.
        /// </summary>
        private List<CallbackWithType> callbacks;

        public MessagingHelper()
        {
            callbacks = new List<CallbackWithType>();
        }

        /// <summary>
        /// Adds an event listener of the appropriate type.
        /// </summary>
        /// <param name="listener">Listener to add.</param>
        /// <param name="type">Type of event to which the listener is subscribing.</param>
        public void Subscribe(MegavaniaEventCallback callback, MegavaniaEventType type, string name)
        {
            callbacks.Add(new CallbackWithType() { callback = callback, type = type, ListenerName = name } );
        }

        /// <summary>
        /// Dispatches the event to any interested parties.
        /// </summary>
        /// <param name="evt">The event to dispatch.</param>
        public void DispatchEvent(IMegavaniaEvent evt)
        {
            // Use LINQ to grab event listeners that are listening to this type
            var interestedListeners =
                from l in callbacks
                where l.type == evt.EventType
                      && (evt.ListenerNames == null || evt.ListenerNames.Length == 0 || evt.ListenerNames.Contains(l.ListenerName))
                select l;
            foreach (var intListener in interestedListeners)
            {
                intListener.callback(evt);
            }
        }

    }
}
